package com.xuexuehai.carrecommand.interceptor;

import com.xuexuehai.carrecommand.entity.Privs;
import com.xuexuehai.carrecommand.exception.enums.SysStatusEnums;
import com.xuexuehai.carrecommand.exception.user.InvalidUserException;
import com.xuexuehai.carrecommand.exception.user.NotLoginException;
import com.xuexuehai.carrecommand.exception.user.UserPrivsIncorrectException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xuexuehai
 * @mailBox xuehai.xue@QQ.com
 * @date 2021/8/21 9:53 下午
 */
public class AuthorityInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler)
            throws Exception {

        //根据前端 localStorage存储的token，获取redis缓存中的用户权限
        List<LinkedHashMap> privsList = (List<LinkedHashMap>) redisTemplate.opsForValue().get(request.getParameter("token"));



        //如果用户没登录，则获取不到权限list，因此当privsList == null 时，表示用户未登录
        if(privsList == null){
            throw new NotLoginException(SysStatusEnums.NOT_LOGIN.getMsg());
        }else{

            List<Object> list = new ArrayList<>();
            for(LinkedHashMap p: privsList){
                list.add(p.get("nameRole"));
            }
            String function = request.getRequestURI();
            String[] content = function.split("/");

            String privsRequest = content[content.length-1];
            System.out.println(privsRequest);


            if(list.contains(privsRequest)){
                return true;
            }else{
                throw new UserPrivsIncorrectException(SysStatusEnums.INCORRECT_USER_PRIVS.getMsg());
            }
        }
    }
}
